#   库的引用
import sys
import platform
import os.path
import ctypes
import sqlite3
import datetime

import PyQt6.QtWidgets as QtWidgets
import PyQt6.QtGui as QtGui
import PyQt6.QtCore as QtCore

import today
import add
import tasks
import calend
import setting

#   定义主界面类
class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.basePath = os.path.dirname(os.path.abspath(__file__))
        self.todayTasks = []
        self.allTasks = []
        self.readData()
        self.initUI()
        self.show()

    #   创建窗口
    def initUI(self):
        #   窗口属性与图标
        self.resize(800, 600)
        self.setWindowTitle("计划清单 v0.2")
        #   设置图标
        self.iconPath = os.path.join(self.basePath, "Icon/done.png")        #   注意：必须使用绝对路径
        self.setWindowIcon(QtGui.QIcon(self.iconPath))
        system = platform.system()
        if system == "Windows":                                             #   设置任务栏图标(Windows专用)
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
        #   设置主题
        self.stylePath = os.path.join(self.basePath, "Qss/main.qss")
        self.qssFile = open(self.stylePath, 'r')
        self.qssStyle = self.qssFile.read()
        self.setStyleSheet(self.qssStyle)

        #   主界面
        self.mainLayout = QtWidgets.QHBoxLayout()
        self.mainLayout.setContentsMargins(6, 6, 6, 6)
        self.mainLayout.setSpacing(6)
        self.setLayout(self.mainLayout)

        #   左侧界面
        self.leftWidget = QtWidgets.QWidget()
        self.leftLayout = QtWidgets.QVBoxLayout()
        self.leftLayout.setContentsMargins(0, 0, 0, 0)
        self.leftLayout.setSpacing(6)
        self.leftWidget.setLayout(self.leftLayout)
        self.mainLayout.addWidget(self.leftWidget)
        self.initLeft()

        #   右侧界面
        self.rightWidget = QtWidgets.QStackedWidget()
        self.mainLayout.addWidget(self.rightWidget)
        self.initRight()

    #   创建左侧界面
    def initLeft(self):
        #   "今日事件"按钮
        self.btnToday = QtWidgets.QPushButton("今日事件")
        self.iconPath = os.path.join(self.basePath, "Icon/today.png")
        self.btnToday.setIcon(QtGui.QIcon(self.iconPath))
        self.btnToday.setCheckable(True)
        self.btnToday.setChecked(True)
        self.btnToday.clicked.connect(self.display)
        self.leftLayout.addWidget(self.btnToday)

        #   "添加任务"按钮
        self.btnNew = QtWidgets.QPushButton("添加任务")
        self.iconPath = os.path.join(self.basePath, "Icon/add.png")
        self.btnNew.setIcon(QtGui.QIcon(self.iconPath))
        self.btnNew.setCheckable(True)
        self.btnNew.clicked.connect(self.display)
        self.leftLayout.addWidget(self.btnNew)

        #   "任务管理"按钮
        self.btnTask = QtWidgets.QPushButton("任务管理")
        self.iconPath = os.path.join(self.basePath, "Icon/task.png")
        self.btnTask.setIcon(QtGui.QIcon(self.iconPath))
        self.btnTask.setCheckable(True)
        self.btnTask.clicked.connect(self.display)
        self.leftLayout.addWidget(self.btnTask)

        #   "日历视图"按钮
        self.btnCalendar = QtWidgets.QPushButton("日历视图")
        self.iconPath = os.path.join(self.basePath, "Icon/calendar.png")
        self.btnCalendar.setIcon(QtGui.QIcon(self.iconPath))
        self.btnCalendar.setCheckable(True)
        self.btnCalendar.clicked.connect(self.display)
        self.leftLayout.addWidget(self.btnCalendar)
        
        #   延长模块
        self.leftLayout.addStretch(1)

        #   "软件设置"按钮
        self.btnSetting = QtWidgets.QPushButton("软件设置")
        self.iconPath = os.path.join(self.basePath, "Icon/setting.png")
        self.btnSetting.setIcon(QtGui.QIcon(self.iconPath))
        self.btnSetting.setCheckable(True)
        self.btnSetting.clicked.connect(self.display)
        self.leftLayout.addWidget(self.btnSetting)

    #   创建右侧界面
    def initRight(self):
        #   今日界面
        self.winToday = today.Today()
        self.rightWidget.addWidget(self.winToday)
        for i in self.todayTasks:
            taskName = i[0]
            newItem = QtWidgets.QListWidgetItem(taskName)
            self.winToday.todoList.addItem(newItem)
        self.winToday.btnOK.clicked.connect(self.taskOK)
        self.winToday.btnNO.clicked.connect(self.taskNo)
        self.winToday.btnIgnore.clicked.connect(self.taskIgnore)

        #   添加任务
        self.winAdd = add.AddTask()
        self.rightWidget.addWidget(self.winAdd)
        self.winAdd.btnCreate.clicked.connect(self.newTask)

        #   任务管理
        self.winTasks = tasks.Tasks()
        self.rightWidget.addWidget(self.winTasks)
        for i in self.allTasks:
            taskName = i[0]
            newItem = QtWidgets.QListWidgetItem(taskName)
            self.winTasks.tasksList.addItem(newItem)
        self.winTasks.btnDel.clicked.connect(self.delTask)

        #   日历视图
        self.winCalendar = calend.Calend()
        self.rightWidget.addWidget(self.winCalendar)
        
        #   软件设置
        self.winSetting = setting.Setting()
        self.rightWidget.addWidget(self.winSetting)

    #   切换界面
    def display(self):
        sender = self.sender()
        if sender.text() == "今日事件":
            self.rightWidget.setCurrentIndex(0)
            self.btnToday.setChecked(True)
            self.btnNew.setChecked(False)
            self.btnTask.setChecked(False)
            self.btnCalendar.setChecked(False)
            self.btnSetting.setChecked(False)
        if sender.text() == "添加任务":
            self.rightWidget.setCurrentIndex(1)
            self.btnToday.setChecked(False)
            self.btnNew.setChecked(True)
            self.btnTask.setChecked(False)
            self.btnCalendar.setChecked(False)
            self.btnSetting.setChecked(False)
        if sender.text() == "任务管理":
            self.rightWidget.setCurrentIndex(2)
            self.btnToday.setChecked(False)
            self.btnNew.setChecked(False)
            self.btnTask.setChecked(True)
            self.btnCalendar.setChecked(False)
            self.btnSetting.setChecked(False)

        if sender.text() == "日历视图":
            self.rightWidget.setCurrentIndex(3)
            self.btnToday.setChecked(False)
            self.btnNew.setChecked(False)
            self.btnTask.setChecked(False)
            self.btnCalendar.setChecked(True)
            self.btnSetting.setChecked(False)

        if sender.text() == "软件设置":
            self.rightWidget.setCurrentIndex(4)
            self.btnToday.setChecked(False)
            self.btnNew.setChecked(False)
            self.btnTask.setChecked(False)
            self.btnCalendar.setChecked(False)
            self.btnSetting.setChecked(True)

    #   读取数据库
    def readData(self):
        dbPath = os.path.join(self.basePath, "Data/data.db")
        conn = sqlite3.connect(dbPath)

        #   如果数据库为空，则创建表
        conn.execute("create table if not exists tasks (\
                     name nchar(10), \
                     detail nchar(10), \
                     date int(10))")
        conn.commit()

        #   读取所有数据
        temp1 = datetime.datetime.today()
        self.today = int("{0:0>4}{1:0>2}{2:0>2}".format(temp1.year, temp1.month, temp1.day))
        temp2 = conn.execute("select * from tasks")
        conn.commit()
        for i in temp2:
            self.allTasks.append(list(i))
            if i[2] == self.today:
                self.todayTasks.append(list(i))

        conn.close()

    #   创建任务
    def newTask(self):
        #   获取界面数据
        name = self.winAdd.textName.text()
        if name == "":
            return 0
        detail = self.winAdd.textDetail.text()
        date = int("{0:0>4}{1:0>2}{2:0>2}".format(self.winAdd.textYear.text(), self.winAdd.textMonth.text(), self.winAdd.textDay.text()))

        #   判断任务是否存在
        for i in self.allTasks:
            if name == i[0] and date == i[2]:
                self.winAdd.btnCreate.setText("————创建失败：任务已经存在————")
                self.winAdd.btnCreate.setStyleSheet("background: #ffb3a7")
                QtCore.QTimer.singleShot(1000, self.winAdd.initAll)
                return 0
        
        #   向数据库中添加内容
        dbPath = os.path.join(self.basePath, "Data/data.db")
        conn = sqlite3.connect(dbPath)
        conn.execute("insert into tasks(name, detail, date) values('{0}', '{1}', {2})".format(name, detail, date))
        conn.commit()
        conn.close()

        #   向任务及事件列表添加内容
        self.allTasks.append([name, detail, date])
        newItem1 = QtWidgets.QListWidgetItem(name)
        self.winTasks.tasksList.addItem(newItem1)
        if date == self.today:
            self.todayTasks.append([name, detail, date])
            newItem2= QtWidgets.QListWidgetItem(name)
            self.winToday.todoList.addItem(newItem2)

        #   提示完成
        self.winAdd.btnCreate.setText("————创建成功————")
        self.winAdd.btnCreate.setStyleSheet("background: #b8e986")
        QtCore.QTimer.singleShot(1000, self.winAdd.initAll)

    #   删除任务
    def delTask(self):
        #   判断是否选中
        selectedRow = self.winTasks.tasksList.currentRow()
        if selectedRow == None:
            return 0
    
        #   删除任务及事件列表中的内容
        selectedName = self.allTasks[selectedRow][0]
        selectedDate = self.allTasks[selectedRow][2]
        del self.allTasks[selectedRow]
        selectedItem1 = self.winTasks.tasksList.takeItem(selectedRow)
        del selectedItem1
        if selectedDate == self.today:
            count = 0
            for i in self.todayTasks:
                if i[0] == selectedName:
                    del self.todayTasks[count]
                    selectedItem2 = self.winToday.todoList.takeItem(count)
                    del selectedItem2
                    break
                count += 1

        #   删除数据库中的内容
        dbPath = os.path.join(self.basePath, "Data/data.db")
        conn = sqlite3.connect(dbPath)
        conn.execute('delete from tasks where name = ? and date = ?', (selectedName, selectedDate))
        conn.commit()
        conn.close()

    #   完成事件
    def taskOK(self):
        if self.winToday.todoList.currentRow == None:
            return 0
        self.winToday.todoList.setStyleSheet("QListView::item:selected{background: #b8e986}")
        QtCore.QTimer.singleShot(500, self.winToday.kickItem)
        del self.todayTasks[self.winToday.todoList.currentRow()]

    #   放弃事件
    def taskNo(self):
        if self.winToday.todoList.currentRow == None:
            return 0
        self.winToday.todoList.setStyleSheet("QListView::item:selected{background: #ffb3a7}")
        QtCore.QTimer.singleShot(500, self.winToday.kickItem)
        del self.todayTasks[self.winToday.todoList.currentRow()]

    #   忽略事件
    def taskIgnore(self):
        if self.winToday.todoList.currentRow == None:
            return 0
        self.winToday.todoList.setStyleSheet("QListView::item:selected{background: #9b9b9b}")
        QtCore.QTimer.singleShot(500, self.winToday.kickItem)
        del self.todayTasks[self.winToday.todoList.currentRow()]

#   运行程序
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    sys.exit(app.exec())